package com.rock.platform.util;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;

public class CookieUtils {
	public static void addCookie(String name, String value) {
		String path = ServletActionContext.getRequest().getContextPath();

		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(-1);
		cookie.setPath(path);
		ServletActionContext.getResponse().addCookie(cookie);
	}

	public static void addCookie(String path, String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(-1);
		cookie.setPath(path);
		ServletActionContext.getResponse().addCookie(cookie);
	}

	public static void addCookie(String domain, String path, String name,
			String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(-1);
		cookie.setDomain(domain);
		cookie.setPath(path);
		ServletActionContext.getResponse().addCookie(cookie);
	}

	public static void removeCookie(String name) {
		Cookie cookie = new Cookie(name, "");
		cookie.setMaxAge(0);
		ServletActionContext.getResponse().addCookie(cookie);
	}

	public static String getCookie(String name) {
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();

		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(name)) {
				return cookie.getValue();
			}
		}

		return null;
	}
}
